package org.xshop.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.xshop.mapper.TGoodsClassifyMapper;
import org.xshop.model.TGoodsClassify;
import org.xshop.service.ITGoodsClassifyService;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.util.InstanceUtil;

/**
 * <p>
 * 商品分类 服务类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2017-03-19
 */
@MotanService(interfaceClass = ITGoodsClassifyService.class)
@CacheConfig(cacheNames = "goodsClassify")
public class GoodsClassifyService extends BaseServiceImpl<TGoodsClassify, TGoodsClassifyMapper>
		implements ITGoodsClassifyService {

	@Override
	public TGoodsClassify queryById(Long id) {
		TGoodsClassify classify = super.queryById(id);
		if (classify != null && classify.getParentId() != null) {
			TGoodsClassify parent = super.queryById(classify.getParentId());
			if (parent != null) {
				classify.setParentName(parent.getClassifyName());
			}
		}
		return classify;
	}

	public List<TGoodsClassify> getAll(Map<String, Object> params) {
		params.put("orderBy", "parent_id,sort_no");
		List<TGoodsClassify> pageInfo = super.queryList(params);
		List<TGoodsClassify> resultList = InstanceUtil.newArrayList();
		Map<Long, Integer> leafMap = InstanceUtil.newHashMap();
		Map<Long, List<TGoodsClassify>> map = InstanceUtil.newHashMap();
		for (TGoodsClassify goodsClassify : pageInfo) {
			if (leafMap.get(goodsClassify.getParentId()) == null) {
				leafMap.put(goodsClassify.getParentId(), 0);
			}
			leafMap.put(goodsClassify.getParentId(), leafMap.get(goodsClassify.getParentId()) + 1);
			if (map.get(goodsClassify.getParentId()) == null) {
				map.put(goodsClassify.getParentId(), new ArrayList<TGoodsClassify>());
			}
			map.get(goodsClassify.getParentId()).add(goodsClassify);
			if (goodsClassify.getParentId() == null || goodsClassify.getParentId() == 0) {
				resultList.add(goodsClassify);
			}
		}
		for (TGoodsClassify goodsClassify : pageInfo) {
			if (map.get(goodsClassify.getId()) != null) {
				resultList.addAll(resultList.indexOf(goodsClassify) + 1, map.get(goodsClassify.getId()));
			}
		}
		return resultList;
	}
}
